# encoding=utf8

import json
from flask import request
from sqlalchemy import or_
from app.models.users import User
from app.models.machine import Machine


class DeviceForm:
    def __init__(self):
        try:
            self.__username = request.form.get('username')
            self.__device = request.form.get('device')
            self.__ip = request.form.get('ip')
            self.__name = request.form.get('name')
            self.__machine = None
            self.__is_valid = True
        except Exception as e:
            self.__is_valid = False

    def _valid_user_name(self):
        if len(self.__username) <= 0:
            return False, None

        user = User.query.filter(or_(User.username.like(self.__username),
                                     User.email.like(self.__username))).first()
        return user is not None, user

    def _valid_device(self):
        return Machine.is_exist(self.__username)

    def on_valid_value(self):
        if not self.__is_valid:
            return False

        user_valid, user = self._valid_user_name()
        if not user_valid:
            return False

        machine_valid, self.__machine = self._valid_device()
        if not machine_valid:
            self.__machine = Machine(code=self.__device, name=self.__name,
                                     user_id=user.get_id(), ip=self.__ip)
            Machine.add(self.__machine)
        if self.__machine is None:
            return False

        return True

    def update_ip(self):
        if not self.__machine:
            return False

        data = json.loads(self.__ip)
        ip = json.dumps(data)
        Machine.update(self.__machine.code, ip)
        return True


class IndexForm:
    def __init__(self, user_id):
        self.__user_id = user_id

    def query_device(self):
        machines = Machine.query.filter_by(user_id=self.__user_id).all()
        data = []
        for machine in machines:
            ips = json.loads(machine.ip)
            for ip in ips:
                item = {'id': machine.id, 'name': machine.name, 'IP': ip['ip'], 'desc': '在线', 'status': 1}
                data.append(item)

        return data

